package com.unitreport.svn;

import java.util.ArrayList;
import java.util.List;

import org.tmatesoft.svn.core.ISVNDirEntryHandler;
import org.tmatesoft.svn.core.SVNDirEntry;
import org.tmatesoft.svn.core.SVNException;
import org.tmatesoft.svn.core.SVNNodeKind;
import org.tmatesoft.svn.core.SVNURL;
import org.tmatesoft.svn.core.internal.io.dav.DAVRepositoryFactory;
import org.tmatesoft.svn.core.internal.wc.DefaultSVNOptions;
import org.tmatesoft.svn.core.wc.SVNClientManager;
import org.tmatesoft.svn.core.wc.SVNLogClient;
import org.tmatesoft.svn.core.wc.SVNRevision;

import com.unitreport.domain.SvnRepositoriesDir;
import com.unitreport.utils.PropertiesUtil;

/**
 * @author Yu Yang
 * 
 *         2013年9月26日
 */
public class SvnUtil {

	private static SVNClientManager manager;
	private static SVNURL repositoryBaseUrl;

	static {
		DAVRepositoryFactory.setup();
		setManager();

	}

	public static List<SvnRepositoriesDir> getSvnRespDirList(String svnUrl) {
		final List<SvnRepositoriesDir> list = new ArrayList<SvnRepositoriesDir>();
		try {
			repositoryBaseUrl = SVNURL.parseURIDecoded(svnUrl);

			SVNLogClient logClient = manager.getLogClient();

			// co时对每个文件目录的处理，实现ISVNDirEntryHandler接口
			logClient.doList(repositoryBaseUrl, SVNRevision.HEAD,
					SVNRevision.HEAD, false, false, new ISVNDirEntryHandler() {

						@Override
						public void handleDirEntry(SVNDirEntry dirEntry)
								throws SVNException {

							SvnRepositoriesDir srd = new SvnRepositoriesDir();
							if(!"".equals(dirEntry.getRelativePath())) {
								
								srd.setId(dirEntry.getURL().toString());
								srd.setText(dirEntry.getRelativePath() + "  " + dirEntry.getRevision());
								srd.setState(dirEntry.getKind().equals(SVNNodeKind.DIR) ? "closed" : "open");
								//srd.setVersion(dirEntry.getRevision());
								
								list.add(srd);
							}
						}
					}); // 列出当前svn地址的目录，对每个文件进行处理
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
		return list;
	}

	private static void doHandleDirEntry(SVNDirEntry dirEntry) {
		
	}

	private static void setManager() {
		DefaultSVNOptions options = new DefaultSVNOptions();

		String name = PropertiesUtil.getPropertiesValue("svn_name");
		String pass = PropertiesUtil.getPropertiesValue("svn_pass");
		if ("".equals(name) || "".equals(pass)) {
			manager = SVNClientManager.newInstance(options);
		} else {
			manager = SVNClientManager.newInstance(options, name, pass); // 如果需要用户名密码
		}
	}
}
